package com.eesujie.xcs.controller;

import com.eesujie.xcs.common.Result;
import com.eesujie.xcs.entity.vo.UserVO;
import com.eesujie.xcs.service.UserService;
import com.eesujie.xcs.util.JsonUtils;
import com.eesujie.xcs.util.JwtUtils;
import com.eesujie.xcs.util.PojoUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author eesujie
 * @since 2023-04-18
 */
@RestController
@RequestMapping( "/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    @Resource
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(String username, String password) {
        var ipv4 = request.getRemoteAddr();
        log.info("ip:{} 的 用户: {} 正在尝试登陆", ipv4, username);

        var user = userService.validUser(username, password);
        user.setIpv4(ipv4);
        user.setUpdateTime(LocalDateTime.now());

        userService.updateById(user);
        UserVO userVO = PojoUtils.parseVO(user);
        response.setHeader(jwtUtils.getHeader(), jwtUtils.generateToken(JsonUtils.toJson(userVO)));

        return Result.success(userVO);
    }
}
